<template>
  <div class="bgc-white relative" style="min-height: calc(100vh - 112px)">
    <div class="ta-center fs16 fw500 p16 border-bottom relative">
      <span>{{ id ? "编辑" : "新增" }}工资表模板</span>
      <div class="absolute left-0 top-0 bottom-0 ml16 pointer flex-center" style="color: rgba(192, 192, 192, 1)" @click="$router.back()">
        <a-icon type="left" class="fs24 mr8" />
      </div>
    </div>
    <template v-if="isEditing">
      <div class="box-shadow p24 flex-center-center m24 br4">
        <a-steps :current="currentStep">
          <a-step title="设置工资项" />
          <a-step title="设置统计项" />
          <a-step title="创建工资表" />
        </a-steps>
      </div>
      <div>
        <EditGongzi
          v-show="currentStep === 0"
          ref="gongzi"
          :id="id"
          :wageItemLst.sync="wageItemLst"
          @cancel="onStepCancel"
          @next="onStepChange(1)"
        />
        <EditTongji
          v-show="currentStep === 1"
          ref="tongji"
          :id="id"
          :wageItemLst="wageItemLst"
          :statItemLst.sync="statItemLst"
          @prev="onStepChange(0)"
          @next="onStepChange(2)"
          @cancel="onStepCancel"
        />
        <EditChuangjian
          v-show="currentStep === 2"
          ref="chuangjian"
          :id="id"
          :name.sync="name"
          :decimalPlaces.sync="decimalPlaces"
          :wageItemLst="wageItemLst"
          :statItemLst="statItemLst"
          @prev="onStepChange(1)"
          @save="onSave"
          @del="onItemDelete"
          @cancel="onStepCancel"
        />
      </div>
      <a-modal v-model="createVisible" title="创建模板" @cancel="doCancel" @ok="doCreate">
        <a-form-item label="模板名称" required :wrapperCol="{ span: 18 }" :labelCol="{ span: 6 }">
          <a-input v-model="name" placeholder="请输入" style="width: 240px" />
        </a-form-item>
        <a-form-item label="尾数处理" required :wrapperCol="{ span: 18 }" :labelCol="{ span: 6 }">
          <a-select v-model="decimalPlaces" :options="decimalPlacesOptions" placeholder="请选择" style="width: 240px" />
        </a-form-item>
      </a-modal>
    </template>
    <div v-else-if="templateItems && templateItems.length > 0" class="ph48 pv24">
      <div class="border-bottom pb16">
        <div class="fs16 fw500">使用指南</div>
        <div class="mt8">设置工资表模板，即对应企业计薪时的月工资表头项目。每位员工只适用一个模板。</div>
      </div>
      <div class="mt24">模板名称：<a-input :value="name" disabled style="width: 240px" /></div>
      <div class="mt16">尾数处理：<a-select :value="decimalPlaces" :options="decimalPlacesOptions" disabled style="width: 240px" /></div>
      <div class="ta-right">
        <a-button type="primary" @click="isEditing = true">编辑</a-button>
      </div>
      <div class="mt24">
        <div class="ph24 border-bottom" style="background: rgba(250, 250, 250, 1); line-height: 48px">名称</div>
        <div v-for="item in templateItems" :key="item.name" class="ph24 border-bottom" style="line-height: 48px">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import EditGongzi from "./editGongzi.vue";
import EditTongji from "./editTongji.vue";
import EditChuangjian from "./editChuangjiang.vue";
import { mapState } from "vuex";
import { decimalPlacesOptions } from "./funcs";
import { isContainByString } from "@/utils/index";
export default {
  name: "",
  components: { EditGongzi, EditTongji, EditChuangjian },
  mixins: [],
  props: {},
  data() {
    return {
      currentStep: 0,
      createVisible: false,
      name: "",
      decimalPlaces: 4,
      decimalPlacesOptions,
      wageItemLst: [],
      statItemLst: [],
      isEditing: false,
      templateItems: []
    };
  },
  computed: {
    ...mapState(["hr"]),
    isAdmin() {
      return isContainByString("contractAdmin");
    },
    companyId() {
      return this.isAdmin ? "0" : this.hr.companyId;
    },
    id() {
      return this.$route.query.id;
    }
  },
  watch: {
    companyId: {
      handler(newVal) {
        if (newVal && !this.id) {
          this.onCreate();
        }
      },
      immediate: true
    },
    id(newVal) {
      // 创建后更新当前路由
      if (newVal) {
        this.initConfig();
      }
    }
  },
  created() {},
  mounted() {
    // 编辑模式下
    if (this.id) {
      this.initConfig();
    }
  },
  methods: {
    loadTemplateDetail() {
      this.$request({
        url: `/salary/api/v1/salaryTemplates/selectOpenSortByTemplateId?salaryTemplateId=${this.id}`
      })
        .then((res) => {
          this.templateItems = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onItemDelete(tab, id) {
      if (tab === "gongzi") {
        this.$refs.gongzi.onOpenChange({ target: { checked: false } }, id);
      } else if (tab === "tongji") {
        this.$refs.tongji.onOpenChange({ target: { checked: false } }, id);
      }
    },
    onSave(lst) {
      if (!this.name) {
        this.$message.warning("模板名称未填写");
        return false;
      }
      const sortedLst = lst.map((item, idx) => ({
        [`${item.statisticalFormula || item.statisticalFormula === null ? "templateCovarianceItemId" : "wageItemId"}`]: item.id,
        sort: idx
      }));
      this.$request({
        url: `/salary/api/v1/salaryTemplates/configurationSalaryTemplate`,
        method: "put",
        data: {
          id: this.id,
          companyId: this.companyId,
          name: this.name,
          decimalPlaces: this.decimalPlaces,
          issue: false,
          openWageItemListVOList: sortedLst.filter((item) => item.wageItemId),
          openCovarianceItemListVOList: sortedLst.filter((item) => item.templateCovarianceItemId)
        }
      })
        .then((res) => {
          this.$message.success("模板配置成功");
          this.$router.back();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onStepChange(nextStep) {
      this.currentStep = nextStep;
      if (nextStep === 1) {
        this.$refs.tongji.loadData();
      } else if (nextStep === 2) {
        this.$refs.chuangjian.initData();
      }
    },
    onStepCancel() {
      this.$router.back();
    },
    initConfig() {
      let temp = localStorage.getItem("xinzimubanTemp");
      if (temp) {
        temp = JSON.parse(temp);
        this.name = temp.name;
        this.decimalPlaces = temp.decimalPlaces;
        this.loadTemplateDetail();
      }
    },
    onCreate() {
      this.isEditing = true;
      this.name = "";
      this.createVisible = true;
    },
    doCreate() {
      if (!this.name) {
        this.$message.warning("内容未填写");
        return false;
      }
      this.$request({
        url: `/salary/api/v1/salaryTemplates`,
        method: "post",
        data: {
          companyId: this.companyId,
          name: this.name,
          decimalPlaces: this.decimalPlaces,
          issue: false
        }
      })
        .then((res) => {
          this.createVisible = false;
          localStorage.setItem("xinzimubanTemp", JSON.stringify(res.data));
          this.$router.replace(`${this.$route.path}?id=${res.data.id}`);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    doCancel() {
      this.createVisible = false;
      this.$router.back();
    }
  }
};
</script>
<style lang="scss"></style>
